package com.lujieni.netty.c3;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;

import java.net.InetSocketAddress;
import java.util.Scanner;

public class CloseEventClient {
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup group = new NioEventLoopGroup();
        ChannelFuture cf = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new StringEncoder());
                    }
                })
                .connect(new InetSocketAddress("localhost", 8081)); //truly execute connection thread is in NioEventLoopGroup its async

        cf.sync(); //wait until connection has been established
        Channel channel = cf.channel();

        new Thread(()->{
            while (true){
                Scanner scanner = new Scanner(System.in);
                String s = scanner.nextLine();
                if("q".equals(s)){
                    channel.close(); // async close
                    break;
                }else{
                   channel.writeAndFlush(s);
                }
            }
        }, "input").start();


        channel.closeFuture().addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                System.out.println(Thread.currentThread().getName() + " client close channel done");
                group.shutdownGracefully(); //shutdown the thread group
            }
        });

    }
}
